package com.kun.hosp.service.impl;

import cn.hutool.core.bean.BeanUtil;

import cn.hutool.json.JSONUtil;
import com.alibaba.excel.util.StringUtils;

import com.kun.hosp.repository.DepartmentRepository;

import com.kun.model.entity.hosp.Department;
import com.kun.model.vo.hosp.DepartmentQueryVo;
import com.kun.model.vo.hosp.DepartmentVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import  com.kun.hosp.service.DepartmentService;
/**
 * @Author zhoukun
 * @Date 2021/5/3 12:06
 */
@Service
@Slf4j
public class DepartmentServcieImpl implements DepartmentService {
    @Autowired
    private DepartmentRepository departmentRepository;


    /**
     * 上传科室信息
     *
     * @param paramMap
     */
    @Override
    public void saveDepartmen(Map<String, Object> paramMap) {
        //将map集合转hospital
        String param = JSONUtil.toJsonStr(paramMap);
        log.info("{}"+param);
        Department department = JSONUtil.toBean(param, Department.class);
        Department departmentByDepcode = departmentRepository.findDepartmentByDepcode(department.getDepcode());
        if(BeanUtil.isEmpty(departmentByDepcode))
        {
            //添加
            department.setCreateTime(new Date());
            department.setUpdateTime(new Date());
            department.setIsDeleted(0);
            departmentRepository.save(department);
        }else {
            //修改
            BeanUtil.copyProperties(departmentByDepcode,department);
            departmentRepository.save(department);
        }

    }

    /**
     * 分页查询
     * paramMap
     * @return
     */
    @Override
    public Page<Department> selectPage(Map<String, Object> paramMap) {
        //获取参数
        String hoscode = (String)paramMap.get("hoscode");
        String depcode = (String)paramMap.get("depcode");
        //设置查询条件
        DepartmentQueryVo departmentQueryVo = new DepartmentQueryVo();
        departmentQueryVo.setHoscode(hoscode);
        departmentQueryVo.setDepcode(depcode);
        Department department = new Department();
        BeanUtils.copyProperties(departmentQueryVo, department);
        department.setIsDeleted(0);

        //获取分页参数
        int page = StringUtils.isEmpty(paramMap.get("page")) ? 1 : Integer.parseInt((String)paramMap.get("page"));
        int limit = StringUtils.isEmpty(paramMap.get("limit")) ? 10 : Integer.parseInt((String)paramMap.get("limit"));

        //创建Pageable 对象
        Sort sort=Sort.by(Sort.Direction.DESC,"createTime");
        Pageable pageable= PageRequest.of(page-1,limit,sort);
        //创建匹配器，即如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true); //改变默认大小写忽略方式：忽略大小写
        //创建实例
        Example<Department> example = Example.of(department, matcher);
        Page<Department> all = departmentRepository.findAll(example, pageable);
        return all;
    }

    /**
     * 删除科室
     */
    @Override
    public void remove(String depcode) {
        Department departmentByDepcode = departmentRepository.findDepartmentByDepcode(depcode);
        if (BeanUtil.isNotEmpty(departmentByDepcode))
        {
            departmentRepository.deleteDepartmentByDepcode(depcode);
        }

    }

    /**
     * 查询所有科室
     *
     * @param hoscode
     * @return
     */
    @Override
    public List<DepartmentVo> findDeptTree(String hoscode) {
        //创建list集合，用于最终数据封装
        List<DepartmentVo> result = new ArrayList<>();

        //根据医院编号，查询医院所有科室信息
        Department departmentQuery = new Department();
        departmentQuery.setHoscode(hoscode);
        Example example = Example.of(departmentQuery);
        //所有科室列表 departmentList
        List<Department> departmentList = departmentRepository.findAll(example);

        //根据大科室编号  bigcode 分组，获取每个大科室里面下级子科室
        Map<String, List<Department>> deparmentMap =
                departmentList.stream().collect(Collectors.groupingBy(Department::getBigcode));
        //遍历map集合 deparmentMap
        for(Map.Entry<String,List<Department>> entry : deparmentMap.entrySet()) {
            //大科室编号
            String bigcode = entry.getKey();
            //大科室编号对应的全局数据
            List<Department> deparment1List = entry.getValue();
            //封装大科室
            DepartmentVo departmentVo1 = new DepartmentVo();
            departmentVo1.setDepcode(bigcode);
            departmentVo1.setDepname(deparment1List.get(0).getBigname());

            //封装小科室
            List<DepartmentVo> children = new ArrayList<>();
            for(Department department: deparment1List) {
                DepartmentVo departmentVo2 =  new DepartmentVo();
                departmentVo2.setDepcode(department.getDepcode());
                departmentVo2.setDepname(department.getDepname());
                //封装到list集合
                children.add(departmentVo2);
            }
            //把小科室list集合放到大科室children里面
            departmentVo1.setChildren(children);
            //放到最终result里面
            result.add(departmentVo1);
        }
        //返回
        return result;
    }

    @Override
    public String getDepName(String hoscode, String depcode) {
        return departmentRepository.findDepartmentByHoscodeAndDepcode(hoscode,depcode).getDepname();
    }
}
